package cn.nohan.funplay.module.member.mongo.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;
import java.util.List;

/**
 * @author caozhipeng
 * @date 2025/7/21
 */
//@Configuration
public class GlobalJacksonConfig {
    // 解决方案：使用Primary确保正确实例
//    @Bean
//    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();

        // 创建模块并配置
        SimpleModule module = new SimpleModule();
        module.setSerializerModifier(new ListNullSerializerModifier());

        mapper.registerModule(module);
        return mapper;
    }

    private static class ListNullSerializerModifier extends BeanSerializerModifier {
        @Override
        public List<BeanPropertyWriter> changeProperties(
                SerializationConfig config,
                BeanDescription beanDesc,
                List<BeanPropertyWriter> beanProperties
        ) {
            System.out.println("处理类: " + beanDesc.getBeanClass().getName());

            for (BeanPropertyWriter writer : beanProperties) {
                JavaType type = writer.getType();
                if (type.isCollectionLikeType() || type.isArrayType()) {
                    writer.assignNullSerializer(new NullListSerializer());
                } else if (type.getRawClass().equals(String.class)) {
                    writer.assignNullSerializer(new NullStringSerializer());
                }


            }
            return beanProperties;
        }
    }

    private static class NullListSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeStartArray();
            gen.writeEndArray();
        }
    }

    private static class NullStringSerializer extends JsonSerializer<Object> {
        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
            gen.writeString("");
        }
    }
}
